//
//  ZLQFirstPageVC.swift
//  GoTravel
//
//  Created by lanou3g on 16/3/9.
//  Copyright © 2016年 SHH. All rights reserved.
//

import UIKit

class ZLQFirstPageVC: UITableViewController,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {

    var flowLayout:UICollectionViewFlowLayout?
    var collectionV:UICollectionView?
    
    let urlSing1 = "http://q.chanyouji.com/api/v1/search.json?q="
    let urlSing2 = "&search_type=destination"
    
//    let urlSting3 = "http://q.chanyouji.com/api/v1/search.json?q=31&search_type="
//    let urlSting4 = "destination"
    
    var str = Int()
    var string = String() //上个页面传过来的title
    
    
    var dataArray = Array<ZLQFirstModel>()
    var dataArray2 = Array<ZLQFirstHeaderModel>()
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.whiteColor()
        
        self.tableView.registerClass(ZLQFirstPageCell.classForCoder(), forCellReuseIdentifier: "cell")
        self.navigationItem.title = self.string
        
        addCollectionView()
        dataAnalysis()
        
    }
    
    func addCollectionView() {

        flowLayout = UICollectionViewFlowLayout()
        flowLayout?.sectionInset = UIEdgeInsetsMake(0, 0,0, 0)
        flowLayout?.itemSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height*0.3)
        flowLayout?.minimumLineSpacing = 0
        flowLayout?.scrollDirection = .Horizontal
        
        collectionV = UICollectionView(frame: CGRectMake(0,0,self.view.frame.size.width,self.view.frame.size.height*0.3), collectionViewLayout: flowLayout!)
        collectionV?.bounces = false
        collectionV?.pagingEnabled = true
        collectionV?.delegate = self
        collectionV?.dataSource = self
        collectionV?.backgroundColor = UIColor.whiteColor()
        
        let nib = UINib(nibName:"ZLQFirstHeaderCell", bundle: nil)
        self.collectionV?.registerNib(nib, forCellWithReuseIdentifier: "myCell")
    
         self.tableView.tableHeaderView = collectionV
        
        dataAnalysis2()
        
    }
    func dataAnalysis2() {
    
        let str1:String = urlSing1 + String(self.str) + urlSing2
        let url = NSURL(string: str1)
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithURL(url!) { (data:NSData?, re:NSURLResponse?, error:NSError?) -> Void in
            
            do {
                let dic:NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary
                let dict:NSDictionary = dic["data"] as! NSDictionary
                let arr:NSArray = dict["user_activities"] as! NSArray
                let dicti:NSDictionary = arr[0] as! NSDictionary
                let arra:NSArray = dicti["contents"] as! NSArray
                for dictDic in arra {
                
                    let model = ZLQFirstHeaderModel()
                    model.setValuesForKeysWithDictionary(dictDic as! [String:AnyObject])
                    self.dataArray2.append(model)
                
                }
            
            } catch {}
            
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.collectionV?.reloadData()
            })
        }
        task.resume()
    }
 
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataArray2.count
    }
    
     func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cellid = collectionView.dequeueReusableCellWithReuseIdentifier("myCell", forIndexPath: indexPath) as? ZLQFirstHeaderCell
        
        let model:ZLQFirstHeaderModel = self.dataArray2[indexPath.row]
        cellid?.headerL.text = model.caption
        cellid?.headerV.sd_setImageWithURL(NSURL(string: model.photo_url!))
        
        
        return cellid!
    }
    
    
    func dataAnalysis() {
    
//        let infpirationModel = ZLQInspirationModel()
//        let str = String(infpirationModel.idInt)
        let url = NSURL(string: urlSing1 + String(self.str) + urlSing2)
        print(self.str)
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithURL(url!) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
            print(data!)
            do {
                let dic:NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary
                let dict:NSDictionary = dic["data"] as! NSDictionary
                for diction in (dict["destinations"] as! NSArray) {
                
                    let model = ZLQFirstModel()
//                    print(diction["inspiration_activities_count"])
                    model.setValuesForKeysWithDictionary(diction as! [String : AnyObject])
                    print(model.inspiration_activities_count)
                    self.dataArray.append(model)
                }
                
            } catch {
            
            }
            
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.tableView.reloadData()
            })
            
            
        }
    
        task.resume()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return self.dataArray.count
    }

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return self.view.frame.size.height*0.15
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as? ZLQFirstPageCell
        let model = dataArray[indexPath.row]
//        print(model.photo_url!)
        cell?.nameImage?.sd_setImageWithURL(NSURL(string: model.photo_url!))
        cell?.nameL?.text = model.name!
        let string = model.inspiration_activities_count!
//        print(model.inspiration_activities_count!)
        cell?.numberL?.text = "哈哈 一共有" + String(string) + "条旅行灵感耶!"


        return cell!
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        let a = ZLQSecondPageTC()
        a.aId = self.dataArray[indexPath.row].idInt!
        a.string = self.dataArray[indexPath.row].name!
        self.navigationController?.pushViewController(a, animated: true)
        
    }


    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
